package es.caeboxapps.game;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.Facebook;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.google.example.games.basegameutils.BaseGameActivity;

import es.caeboxapps.game.utils.Utils;

public class MenuActivity extends BaseGameActivity {
	Session session;
	Facebook facebook;
	SharedPreferences mPrefs;
	ProfilePictureView profilePictureView;
	private int REQUEST_LEADERBOARD = 0;

	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.menu_activity);
		
		GameApplication.internet = Utils.haveNetworkConnection(this);

		CheckBox checkBoxSonido = (CheckBox) findViewById(R.id.checkBoxSonido);
		Button btnIniciarJuego = (Button) findViewById(R.id.buttonIniciarJuego);
		Button btnMostrarPuntuaciones = (Button) findViewById(R.id.buttonMostrarPuntuaciones);
		Button btnInfo = (Button) findViewById(R.id.buttonInfo);
		
		checkBoxSonido.setChecked(true);
		checkBoxSonido.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							GameApplication.sonidoActivo = true;
						} else {
							GameApplication.sonidoActivo = false;
						}

					}
				});

		// Set Type Face
		Typeface font = Typeface.createFromAsset(getAssets(),"Bunaken_Underwater.ttf");
		btnIniciarJuego.setTypeface(font);
		btnMostrarPuntuaciones.setTypeface(font);
		btnInfo.setTypeface(font);
		checkBoxSonido.setTypeface(font);

		
			LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
			// // start Facebook Login Automatically
			// Session.openActiveSession(this, true, new
			// Session.StatusCallback() {
			// start Facebook Login by button
			authButton.setSessionStatusCallback(new Session.StatusCallback() {
				// callback when session changes state
				@Override
				public void call(Session session, SessionState state,
						Exception exception) {
					setSession(session);
					loginFacebook();
				}
			});

			loginGoogle();
			loginFacebook();
		// Codigo que obtiene el hashkey para introducirlo en la web de facebook
		// developers, no es importante. En la version final hay que borrarlo
		try {
			PackageInfo info = getPackageManager().getPackageInfo("es.caeboxapps.game", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.d("KeyHash:",Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}

	}

	// ---------------------------------------------------------------------------
	// INICIAR JUEGO
	// -----------------------------------------------------------------------
	public void iniciarJuego(View view) {
		Intent intent = new Intent(this, QuestionActivity.class);
		startActivity(intent);
		GameApplication.listaPreguntas = Utils.getQuestions(this);
		finish();
	}
	
	public void mostrarPuntuaciones(View view){
		onShowLeaderboardsRequested();		
	}
	
	public void info(View view){
		Intent intent = new Intent(this, InfoActivity.class);
		startActivity(intent);
	}

	protected void onResume() {
		super.onResume();

		// Reseteamos valores
		// ------------------
		GameApplication.posicionPreguntaActual = 0;
		GameApplication.numeroPreguntaActual = 1;
		GameApplication.numeroSaltos = GameApplication.NUMERO_DE_SALTOS;
		GameApplication.lifes = GameApplication.NUMERO_DE_VIDAS;
		GameApplication.nivelPartida = 1;
	}

	// ---------------------------------------------------------------------------
	// Metodos usados para facebook
	// -----------------------------------------------------------------------

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (Session.getActiveSession() != null && resultCode == RESULT_OK) {
			Session.getActiveSession().onActivityResult(MenuActivity.this,
					requestCode, resultCode, data);
		}

	}

	public void loginFacebook() {
		profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
		session = Session.getActiveSession();
		if (session != null) {
			if (session.isOpened()) {
				profilePictureView.setVisibility(View.VISIBLE);

				// Comprueba si se estan obteniendo los permisos de
				// publicacion
				// if (pendingPublishReauthorization &&
				// state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
				// pendingPublishReauthorization = false;
				// publishStory();
				// }

				Request.newMeRequest(session, new Request.GraphUserCallback() {

					// callback after Graph API response with user
					// object
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							// obtiene la imagen de perfil del
							// usuario y la coloca
							profilePictureView.setProfileId(user.getId());
							// getFriends();
						}
					}
				}).executeAsync();
			} else if (session.isClosed()) {
				profilePictureView.setVisibility(View.INVISIBLE);
			}
		}

	}

	// Metodo para obtener los amigos de Facebook
	// private void getFriends() {
	// Session session = Session.getActiveSession();
	//
	// Request.newMyFriendsRequest(session, new GraphUserListCallback() {
	// @Override
	// public void onCompleted(List<GraphUser> users, Response response) {
	// // TODO Auto-generated method stub
	// if (response.getError() == null) {
	// for (int i = 0; i < users.size(); i++) {
	// Log.e("users", "users " + users.get(i).getName());
	// }
	// } else {
	// Toast.makeText(MenuActivity.this,
	// response.getError().getErrorMessage(),
	// Toast.LENGTH_SHORT).show();
	// }
	// }
	// }).executeAsync();
	// }

	// ---------------------------------------------------------------------------
	// Metodos usados para Google
	// -----------------------------------------------------------------------

	public void loginGoogle() {
		// start the sign-in flow
		beginUserInitiatedSignIn();
	}

	@Override
	public void onSignInFailed() {
		// TODO Auto-generated method stub
			String mensaje = this.getString(R.string.no_google);
			Utils.mostrarDialogError(this, mensaje);
	}

	@Override
	public void onSignInSucceeded() {
		// TODO Auto-generated method stub
	}

    public void onShowLeaderboardsRequested() {
        if (isSignedIn()) {
            startActivityForResult(getGamesClient().getLeaderboardIntent(getString(R.string.leaderboard_mejores_puntuaciones)), REQUEST_LEADERBOARD);
        } else {
            showAlert("No leaderBoard disponible");
        }
    }
	
	
	
	// ---------------------------------------------------------------------------
	// Getters & Setters
	// -----------------------------------------------------------------------

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

}
